#include "PathTracerWidget.h"
#include <QtCore/QString>
#include <QtGui/QPainter>
#include <QtGui/QtEvents>

PathTracerWidget::PathTracerWidget(QWidget* parent /*= nullptr*/):
	QWidget(parent), m_mray("scene.xml")
{
	m_refreash = true;
	setWindowTitle(QString("mray0.3 - a mini ray tracer"));
	resize(m_mray.width(), m_mray.height());
	setFocusPolicy(Qt::StrongFocus);
	setFixedSize(width(), height());
	setWindowFlags(Qt::Dialog | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
}

void PathTracerWidget::paintEvent(QPaintEvent* e)
{
	if(m_refreash){
		uchar* data = m_mray.render(0);
		m_image = QImage(data, m_mray.width(), m_mray.height(), QImage::Format_RGB888).mirrored();
		m_refreash = false;
	}

	QPainter painter(this);
	painter.drawImage(0, 0, m_image, 0, 0, m_image.width(), m_image.height());

}

void PathTracerWidget::mousePressEvent(QMouseEvent* e)
{
	//x y in screen space
	int x = e->x();
	int y = m_mray.height() - e->y();

	printf("x:%d y:%d\n", x, y);
}

void PathTracerWidget::keyPressEvent(QKeyEvent * e)
{
	float moveSpeed = 0.1f;
	float rotSpeed = 0.1f;

	m_refreash = true;

	switch(e->key()){
	case Qt::Key_W:
		m_mray.move(0, moveSpeed, mray::MRay::Forward);
		break;
	case Qt::Key_S:
		m_mray.move(0, moveSpeed, mray::MRay::Backward);
		break;
	case Qt::Key_A:
		m_mray.move(0, moveSpeed, mray::MRay::Left);
		break;
	case Qt::Key_D:
		m_mray.move(0, moveSpeed, mray::MRay::Right);
		break;
	case Qt::Key_Up:
		m_mray.rotate(0, rotSpeed, mray::MRay::Up);
		break;
	case Qt::Key_Down:
		m_mray.rotate(0, rotSpeed, mray::MRay::Down);
		break;
	case Qt::Key_Left:
		m_mray.rotate(0, rotSpeed, mray::MRay::Left);
		break;
	case Qt::Key_Right:
		m_mray.rotate(0, rotSpeed, mray::MRay::Right);
		break;
	case Qt::Key_PageUp:
		m_mray.move(0, moveSpeed, mray::MRay::Up);
		break;
	case Qt::Key_PageDown:
		m_mray.move(0, moveSpeed, mray::MRay::Down);
		break;
	default:
		m_refreash = false;
		break;
	}

	update();
}
